<?php


namespace AppBundle\Controller;

use AppBundle\Common\Paginator;
use Symfony\Component\HttpFoundation\Request;

class EntryController extends BaseController{

/*
 * 列出所有留言
 */
    public function listAction(Request $request){
        $q=$request->query->get('q');
        $condition=array('title'=>$q);
        $paginator = new Paginator(
            $this->get('request'),
            $this->getEntryService()->countEntries($condition),
            4
        );
        $entries= $this->getEntryService()->searchEntries($condition,array(),$paginator->getOffsetCount(),$paginator->getPerPageCount());

        return $this->render('entry/index.html.twig',array('entries'=>$entries,'paginator'=>$paginator));
    }

    /*
     * 显示单条留言
     */
  public function showAction($id){
    $entry=  $this->getEntryService()->getEntry($id);
    return $this->render('entry/show.html.twig',array(
        'entry'=>$entry
    ));
  }

    /*
     * 创建留言
     */
    public function newAction(Request $request){
           return $this->render('entry/new.html.twig',array(
        ));
    }
    public function createAction(Request $request){
        $fields=$request->request->all();//提交表单数据 a
        $this->getEntryService()->createEntry($fields);
        return $this->render('entry/new.html.twig');
    }
    /*
     * 编辑留言
     */
    public function editAction($id){

        //获取留言
        $entry = $this->getEntryService()->getEntry($id);


        return $this->render('entry/edit.html.twig',array(
            'entry'=>$entry
        ));
    }

    /*
     * 处理编辑表单提交
     */
    public function updateAction(Request $request,$id){

        $fields = $request->request->all();
        $entry=$this->getEntryService()->updateEntry($id,$fields);

        return $this->render('entry/edit.html.twig',array(
            'entry'=>$entry
        ));
    }

    /*
     * 删除一条留言
     */
    public function deleteAction(Request $request,$id){

        if($request->getMethod() == "POST"){
            $this->getEntryService()->deleteEntry($id);
        }

        return $this->redirect($this->generateUrl('homepage'));
    }

    protected function getEntryService(){
        return $this->biz->service('Entry:EntryService');
    }
}
